// pages/searchResult/searchResult.js
let url_js = require("../../utils/url.js");
let user_js = require("../../utils/user.js");
let common_js = require("../../utils/common.js");
let search_js = require("../../utils/search.js");
let sys_js = require("../../utils/system.js");
let cart_js = require("../../utils/cart.js");
let ubt_js = require("../../utils/ubt.js");
let name_js = require("../../utils/ubtButtonName.js");
let api = require("../../utils/apiRequest.js");

Page({

  /**
   * 页面的初始数据
   */
  data: {
    sysInfo: null,
    userInfo: null,
    containerTouchmove: '',
    pageScrollTop: 0,
    goodsPropertyInfo: {
      pageShow: false, //页面展示
      dismiss: false, //手动设置隐藏，当属性页面隐藏完成后，pageShow设置false
    },
    keyword: '',
    orderType: 1, //1按销量倒序,2按价格升序,3按价格降序。
    orderTypeList: [], //map数组
    segSelectedIndex: 0,
    moveLineStartLeft: 0,
    moveAnimation: {
      data: null,
      animation: null
    },
    rotateAnimation: {
      data: null,
      animation: null,
      rotate: 0
    },
    noSearchUrl: url_js.imgUrl + "no_searchs.png",
    contentStatus: -1, //0；搜索无结果 1：有结果
    favirotesList: [],
    faviPageInfo: {
      curPage: 1,
      pageSize: 10,
      noMore: false
    },
    resultList: [],
    pageInfo: {
      curPage: 1,
      pageSize: 10,
      noMore: false
    },
    addCartSelctedGoodsInfo: null,
    cartCount: 0, //购物车数量
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //业务埋点
    ubt_js.myPageView(common_js.currentPageName(), options);
    //1.禁止转发
    wx.hideShareMenu();
    //0.获取信息
    this.initData(options);
    //获取信息
    this.getSystemInfo();
    //3.请求数据
    this.requestToSearch(this.data.keyword, this.data.orderType, 1, 10);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    // 业务埋点
    ubt_js.myPageViewOut(common_js.currentPageName());
  },

  //按钮点击事件
  //禁止滚动
  preventTouchMove: function () {},

  //获取屏幕信息
  getSystemInfo: function () {
    if (this.data.sysInfo) {
      let systemInfo = this.data.sysInfo;
      let moveLineL = systemInfo.screenWidth / 4.0 - 24;
      this.setData({
        moveLineStartLeft: moveLineL,
      });
      return
    }
    //获取
    wx.getSystemInfo({
      success: res => {
        //处理滚动条的位置
        let systemInfo = res;
        let moveLineL = res.screenWidth / 4.0 - 24;
        this.setData({
          moveLineStartLeft: moveLineL,
          sysInfo: systemInfo
        });
      }
    })
  },

  //初始化数据
  initData: function (options) {
    let tempUserInfo = user_js.userInfo();
    let tmpKeyword = options.keyword ? options.keyword : '';
    this.setData({
      keyword: tmpKeyword,
      cartCount: cart_js.count(),
      sysInfo: sys_js.systemInfo(),
      userInfo: tempUserInfo
    });
  },

  //根据关键词去搜索数据
  requestToSearch: function (keyword, orderType, curPage, pageSize) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      curPage: curPage,
      pageSize: pageSize,
      keyword: keyword,
      orderType: orderType,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.searchUrl, data).then(res => {
      this.handleSearchResponseData(res, curPage, pageSize, keyword);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的搜索数据
  handleSearchResponseData: function (res, curPage, pageSize, keyword) {

    //记录搜索关键词
    search_js.addHistoryWithKeyWord(keyword);

    //
    if (res.result.length > 0) {
      let tmpResultList = this.data.resultList.concat(res.result);
      //pageInfo
      let tmpPageInfo = this.data.pageInfo;
      if (res.page.pages <= curPage) {
        tmpPageInfo.noMore = true;
      } else {
        tmpPageInfo.curPage++;
      }

      //设置map
      let tmpMap = new Map(this.data.orderTypeList);
      let obj = null;
      if (tmpMap.get(this.data.orderType)) {
        obj = tmpMap.get(this.data.orderType);
      } else {
        obj = {};
      }
      obj.pageInfo = tmpPageInfo;
      obj.list = tmpResultList;
      tmpMap.set(this.data.orderType, obj);

      this.setData({
        contentStatus: 1,
        pageInfo: tmpPageInfo,
        resultList: tmpResultList,
        orderTypeList: [...tmpMap]
      });
    } else {
      let tmpfaviPageInfo = {
        curPage: 1,
        pageSize: 10,
        noMore: false
      };
      this.setData({
        contentStatus: 0,
        favirotesList: [],
        faviPageInfo: tmpfaviPageInfo
      });
      //请求猜你喜欢接口
      this.requestToGetRecommendGuess(this.data.faviPageInfo.curPage, this.data.faviPageInfo.pageSize);
    }
  },

  //猜你喜欢
  requestToGetRecommendGuess: function (curPage, pageSize) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      curPage: curPage,
      pageSize: pageSize,
      shopId: this.data.userInfo.ztd.id
    }
    api.wxRequest(url_js.recommendGuessUrl, data).then(res => {
      this.handleRecommendGuessData(res, curPage, pageSize);
    }).catch(err => {
      common_js.log(err);
    });
  },

  //处理返回的猜你喜欢的数据
  handleRecommendGuessData: function (res, curPage, pageSize) {
    if (res.result.length > 0) {
      let tmpResultList = this.data.favirotesList.concat(res.result);
      //pageInfo
      let tmpPageInfo = this.data.faviPageInfo;
      if (res.page.pages <= curPage) {
        tmpPageInfo.noMore = true;
      } else {
        tmpPageInfo.curPage++;
      }

      this.setData({
        faviPageInfo: tmpPageInfo,
        favirotesList: tmpResultList,
      });
    }
  },

  //搜索内容输入
  bindSearchInput: function (e) {
    let tmpKeyword = e.detail.value;
    this.setData({
      keyword: tmpKeyword
    });
  },

  //点击键盘搜索按钮
  onSearchDone: function (e) {
    let tmpKeyword = "";
    if (this.data.keyword.length == 0) {
      common_js.showToast("搜索关键词不能为空！");
      return;
    } else {
      tmpKeyword = this.data.keyword;
    }

    //resetData()
    this.resetAllData();
    //请求数据
    this.requestToSearch(this.data.keyword, this.data.orderType, 1, 10);
  },

  //重置数据
  resetAllData: function () {
    let tmpPageInfo = {
      curPage: 1,
      pageSize: 10,
      noMore: false
    };
    this.moveLineWithIndex(0);
    if (this.data.orderType == 2) {
      this.onPriceArrowRotate();
    }
    this.setData({
      orderType: 1,
      orderTypeList: [],
      contentStatus: -1,
      resultList: [],
      pageInfo: tmpPageInfo
    });
  },

  //购物车
  onCart: function () {
    //跳转购物车
    wx.switchTab({
      url: '/pages/cart/cart'
    });
  },

  //顶部切换
  onseg: function (e) {
    //1按销量倒序,2按价格升序,3按价格降序。
    let index = parseInt(e.currentTarget.dataset.index);
    let tmpOrderType = this.data.orderType;

    if (this.data.segSelectedIndex == index) {
      //默认销量有数据
      if (index == 0) return;
      //价格
      if (index == 1) {
        //升序
        tmpOrderType = (tmpOrderType == 2) ? 3 : 2;
        this.onPriceArrowRotate();
        //有数据，展示，return
        this.showResultData(tmpOrderType);
        this.setData({
          orderType: tmpOrderType,
          segSelectedIndex: index
        });
      }
    } else {
      if (index == 0) {
        if (tmpOrderType == 2) {
          this.onPriceArrowRotate();
        }
        tmpOrderType = 1;
      } else if (index == 1) {
        //默认价格降序
        tmpOrderType = 3;
      }
      this.setData({
        orderType: tmpOrderType,
        segSelectedIndex: index
      });
      //移动线
      this.moveLineWithIndex(index);
      //有数据，展示，return
      this.showResultData(tmpOrderType);
    }
  },

  //展示result数据
  showResultData: function (orderType) {
    let tmpMap = new Map(this.data.orderTypeList);
    if (tmpMap.get(orderType)) {
      let tmpObj = tmpMap.get(orderType);
      this.setData({
        pageInfo: tmpObj.pageInfo,
        resultList: tmpObj.list
      });
    } else {
      //没有数据，请求数据，retun
      let tmpPageInfo = {
        curPage: 1,
        pageSize: 10,
        noMore: false
      }
      this.setData({
        pageInfo: tmpPageInfo,
        resultList: []
      });
      this.requestToSearch(this.data.keyword, orderType, 1, this.data.pageInfo.pageSize);
    }
  },

  moveLineWithIndex: function (index) {
    if (!this.data.moveAnimation.animation) {
      let tempMoveAnimation = this.data.moveAnimation;
      let animation = wx.createAnimation({
        timingFunction: 'ease',
      });
      tempMoveAnimation.animation = animation;
      this.setData({
        moveAnimation: tempMoveAnimation
      });
    }
    let tempMoveAnimation = this.data.moveAnimation;
    let tempTranslateX = (this.data.sysInfo.screenWidth / 2.0) * index;
    tempMoveAnimation.animation.translateX(tempTranslateX).step();
    tempMoveAnimation.data = tempMoveAnimation.animation.export();
    this.setData({
      segSelectedIndex: index,
      moveAnimation: tempMoveAnimation
    });
  },

  onPriceArrowRotate: function () {
    //动画
    if (!this.data.rotateAnimation.animation) {
      let tempRotateAnimation = this.data.rotateAnimation;
      let animation = wx.createAnimation({
        timingFunction: 'ease',
      });
      tempRotateAnimation.animation = animation;
      this.setData({
        rotateAnimation: tempRotateAnimation
      });
    }
    let tempRotateAnimation = this.data.rotateAnimation;
    let tempRotate = (tempRotateAnimation.rotate == -180) ? 0 : -180;
    tempRotateAnimation.rotate = tempRotate;
    tempRotateAnimation.animation.rotate(tempRotate).step();
    tempRotateAnimation.data = tempRotateAnimation.animation.export();
    this.setData({
      rotateAnimation: tempRotateAnimation
    });
  },

  //添加商品
  onGoodsAdd: function (e) {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return
    }

    let index = e.currentTarget.dataset.index;
    let item = this.data.resultList[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      //展示多规格商品
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = false;
        if (skuItem.userBuyLimit && skuItem.userBuyLimit > 0) {
          isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        }
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }

    //埋点
    ubt_js.myClickButton(common_js.currentPageName(), name_js.searchResultAdd);
  },

  //增加购物车
  requestToAddCart: function (skuItem, productId, skuId, num) {
    let data = {
      cityId: this.data.userInfo.ztd.cityId,
      code: user_js.getCode(),
      num: num,
      productId: productId,
      shopId: this.data.userInfo.ztd.id,
      skuId: skuId
    };
    api.wxRequest(url_js.cartAddUrl, data).then(res => {
      this.handleAddCartData(res, skuItem, skuId, num);
    }).catch(err => {
      common_js.log(err);
    });
  },


  //处理添加购物车
  handleAddCartData: function (res, skuItem, skuId, num) {
    cart_js.addCart(skuItem, skuId, num);
    this.setData({
      cartCount: (this.data.cartCount + num)
    });
    common_js.showToast("添加购物车成功");
  },

  //商品详情
  onGoodsDetail: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.resultList[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    })
  },

  //猜你喜欢添加商品
  onFaviGoodsAdd: function (e) {
    if (!user_js.isLogin()) {
      wx.navigateTo({
        url: '../loginIndex/loginIndex'
      });
      return
    }

    let index = e.currentTarget.dataset.index;
    let item = this.data.favirotesList[index];
    if (item.skuList && item.skuList.length > 1) {
      if (item.dimensions.length == 0) {
        common_js.showToast("商品多规格属性不存在！");
        return;
      }
      //多规格,选择规格加入购物车
      let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
      tmpGoodsPropertyInfo.pageShow = true;
      //展示多规格商品
      this.setData({
        addCartSelctedGoodsInfo: item,
        goodsPropertyInfo: tmpGoodsPropertyInfo,
        containerTouchmove: 'preventTouchMove'
      });
    } else {
      //单一规格,直接添加购物车
      if (item.skuList == 0) {
        common_js.showToast("商品sku不存在");
        return;
      }
      //限时抢购单独判断
      if (item.type != 0) {
        let skuItem = item.skuList[0];
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = false;
        if (skuItem.userBuyLimit && skuItem.userBuyLimit > 0) {
          isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        }
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
          })
          return;
        }
      }
      this.requestToAddCart(item.skuList[0], item.id, item.skuList[0].id, 1);
    }
  },

  //猜你喜欢商品详情
  onFaviGoodsDetail: function (e) {
    let index = e.currentTarget.dataset.index;
    let item = this.data.favirotesList[index];
    wx.navigateTo({
      url: '../goodsDetails/goodsDetails?productId=' + item.id
    })
  },

  //商品属性选择
  onGoodsPropertyHidden: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.pageShow = false;
    tmpGoodsPropertyInfo.dismiss = false,
      this.setData({
        containerTouchmove: '',
        goodsPropertyInfo: tmpGoodsPropertyInfo
      });
  },

  //商品属性确定
  onGoodsPropertyEnsure: function (e) {
    //隐藏
    this.onGoodsPropertyHidden();
    if (e) {
      let item = e.detail;
      //限时抢购单独判断
      if (this.data.addCartSelctedGoodsInfo.type != 0) {
        let skuItem = item.sku;
        let cartLimitCount = cart_js.limitSkuCountWithSkuId(skuItem.id);
        let isAlert = false;
        if (skuItem.userBuyLimit && skuItem.userBuyLimit > 0) {
          isAlert = (cartLimitCount == 0) ? (item.count > skuItem.userBuyLimit) : (cartLimitCount >= skuItem.userBuyLimit);
        }
        if (isAlert) {
          common_js.showModal("每人限购" + skuItem.userBuyLimit + "件，超过的件数将以原价支付！", null, true, null, "我知道了", () => {
            this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
          })
          return;
        }
      }
      this.requestToAddCart(item.sku, this.data.addCartSelctedGoodsInfo.id, item.sku.id, item.count);
    }
  },

  //隐藏商品属性页面
  onHidePropertyPageView: function (e) {
    let tmpGoodsPropertyInfo = this.data.goodsPropertyInfo;
    tmpGoodsPropertyInfo.dismiss = true;
    this.setData({
      goodsPropertyInfo: tmpGoodsPropertyInfo
    });
  },

  // 监听用户滑动页面事件
  onPageScroll: function (e) {
    let topY = e.scrollTop + "px";
    this.setData({
      pageScrollTop: topY
    });
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    //猜你喜欢
    if (this.data.contentStatus == 0) {
      //搜索
      if (this.data.faviPageInfo.noMore) return;
      //1. request
      this.requestToGetRecommendGuess(this.data.faviPageInfo.curPage, this.data.faviPageInfo.pageSize);
    } else if (this.data.contentStatus == 1) {
      //搜索
      if (this.data.pageInfo.noMore) return;
      //1. request
      this.requestToSearch(this.data.keyword, this.data.orderType, this.data.pageInfo.curPage, this.data.pageInfo.pageSize);
    }
  },
})